package com.cdqidi.util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.DbKit;



public class IpAuth {
	private static Logger logger = Logger.getLogger(IpAuth.class);
	private static Integer lockeryz	= new Integer(0);
	
	public static void yanzehen(String cid, String ip, JSONObject jo) {
		synchronized (lockeryz) {
			try {
				boolean isIpAuth = false;
				Integer count = null;
				String id = "client_manager_"+cid;
				String json = RedisMgr.getInstance().getProp(id);
				if(StringUtils.isEmpty(cid)){
					jo.put("errcode", 10000);
					jo.put("errmsg", "cid不能为空");
					return;
				}
				if(StringUtils.isEmpty(json)) {
					json = loadCpProduct(cid);
				}
				if (StringUtils.isEmpty(json)) {
					jo.put("errcode", 10001);
					jo.put("errmsg", "cid未在系统注册: "+cid);
					return;
				}
				JSONObject j = JSON.parseObject(json);
				Integer number = j.getInteger("number");
				if(null==number||number==0){
					return;//不验证调用次数和ip地址
				}
				JSONArray ips = j.getJSONArray("ip");
				id = "client_manager_count_"+cid;
				Object object = RedisMgr.getInstance().get(id);
				if (null == object) {
					// 第一次进入
					count = 0;
					RedisMgr.getInstance().set(id, count);
					RedisMgr.getInstance().expire(id, 24 * 60 * 60);
				} else {
					count = (Integer) object;
				}
				if(null==ips){
					jo.put("errcode", 10000);
					jo.put("errmsg", "客户端配置ip地址不能为空");
					return;
				}
				String[] _ips = ips.toArray(new String[]{});
				for (String _ip : _ips) {
					if(_ip.equals(ip)){
						isIpAuth = true;
						break;
					}
				}
				if (!isIpAuth) {
					jo.put("errcode", 10002);
					jo.put("errmsg", "ip地址鉴权失败: " + ip);
					return;
				}
				count = count + 1;
				logger.info("cid: " + cid + ",当前条数: " + count + ",总条数：" + number);
				if (count > number) {
					jo.put("errcode", 10003);
					jo.put("errmsg", "接口调用超过上限");
					return;
				} else {
					RedisMgr.getInstance().set(id, count);
				}

			} catch (ClassNotFoundException | IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static String loadCpProduct(String cpcode){
		try {
			Connection conn = DbKit.getConfig().getConnection();
			try {
				String sql = "select cpcode,cpname,disname,interfaceadd,dxdk,ipaddress,number,csfs from CpProduct where sfsc=0 and cpcode=?";
				PreparedStatement stmt = conn.prepareStatement(sql);
				try {
					stmt.setString(1, cpcode);
					ResultSet rs = stmt.executeQuery();
					try {
						String ipAddress = null;
						JSONObject json = null;
						JSONArray jrr = null;
						Integer number= null;
						if(rs.next()) {
							json = new JSONObject();
							ipAddress = rs.getString("ipaddress");
							number = rs.getInt("number");
		  		    		if(StringUtils.isNotEmpty(ipAddress)){
		  		    			jrr = new JSONArray();
		  		    			String[] ips = ipAddress.split(",");
		  		    			for (String ip : ips) {
		  		    				jrr.add(ip);
		  						}
		  		    			json.put("ip", jrr);
		  		    		}
		  		    		if(null!=number&&number>0) {
		  		    			json.put("number",number);
		  		    		}
		  		    		json.put("disname",rs.getString("disname"));
		  		    		json.put("cpname",rs.getString("cpname"));
		  		    		json.put("interfaceadd",rs.getString("interfaceadd"));
		  		    		json.put("dxdk",rs.getString("dxdk"));
		  		    		json.put("csfs",rs.getInt("csfs"));
		  		    		logger.info("CpProduct,id: " + "client_manager_"+cpcode + ",json: " + json.toJSONString());
		  		    		RedisMgr.getInstance().setProp("client_manager_"+cpcode, json.toJSONString());
		  		    		RedisMgr.getInstance().set("client_manager_count_"+cpcode,0);
		  		    		return json.toJSONString();
						}
					}finally {
						rs.close();
					}
				}finally {
					stmt.close();
				}
			}finally {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}catch(IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}